<template>
  <div class="list-con">
     <div  id='goTop' @click='goTop'  v-show = 'toTop' class="to-top">
       <img src="../assets/images/top.png" alt="" />
     </div>
  </div>
</template>

<script>
export default {
  name: 'scrolls',
  props:{

  },
  data () {
    return {
      msg: '',
      toTop:false,
      stop:false,
      timer:null
    }
  },
  mounted(){
    var vm=this;
    vm.$nextTick(function () {
      window.addEventListener('scroll', vm.needToTop);  //滚动事件监听
    });
  },
  methods:{
    goTop(){
      var vm=this;
     clearInterval(vm.timer);
       vm.timer = setInterval(function() {
        let curHeight = document.documentElement.scrollTop || document.body.scrollTop;
        var now = curHeight;
        var speed = (0 - now) / 8;

        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
        curHeight == 0 && clearInterval(vm.timer);
        document.documentElement.scrollTop = curHeight + speed;
        document.body.scrollTop = curHeight + speed;
        vm.stop = false;
     }, 30);
    },
    needToTop(){
      let curHeight = document.documentElement.scrollTop || document.body.scrollTop;
      let viewHeight = document.documentElement.clientHeight;

      let vm=this;
      this.toTop =   curHeight > viewHeight + 100 ? true :false;

      vm.stop && clearInterval(vm.timer);
      vm.stop = true;

    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

    .to-top{
      position:fixed;
      right:.4rem;
      bottom:1rem;
      width:2rem;
      height:2rem;

      text-align:right;
      z-index:11;

    }
  .to-top img{
     display: block;
    width:2rem;
    height:2rem;
  }
</style>
